package com.fclassroom.logger.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fclassroom.ErrorCode;
import com.fclassroom.logger.entity.LogCacheForSLS;
import com.fclassroom.logger.service.common.ICommonMethodService;
import com.jason.framework.mvc.spring.BaseController;
import com.jason.framework.util.JsonUtil;
import com.jason.framework.util.StringUtil;
import com.jason.framework.util.SystemProperties;

/**
 * 日志系统的http接口，可以收发消息。
 * 
 * @author jason
 */
@Controller
@RequestMapping("/sls")
public class LoggerForSLSController extends BaseController {
	private static final String SEPARATOR = "/";
	private static final String LOG_file_path = SystemProperties.getProperties("LOG_file_path");
	@Autowired
	private LogCacheForSLS logCacheForSLS;
	@Autowired
	private ICommonMethodService commonMethodService;
	protected static final Logger logger = LogManager.getLogger();

	/**
	 * 记录系统和用户日志,单条上传<br/>
	 * 
	 * @param msgType
	 * @param msgKey
	 * @param msg
	 *            单条日志详情
	 * @return
	 */
	@RequestMapping(value = "/recordByMsg")
	public ResponseEntity<String> recordByMsg(HttpServletRequest request, Integer msgType, String msgKey, String msg) {
		String errorCode = ErrorCode.System_error;
		if (msgType != null && StringUtil.isNotEmpty(msg)) {
			if (msgType == 1) {
				try {
					commonMethodService.dealAutoPostSLS(msg);
					errorCode = ErrorCode.Success;
				} catch (Exception e) {
					logger.error("recordByMsg Exception,msgType:{},msg:{},exception:{}", msgType, msg, e.getMessage());
					errorCode = ErrorCode.Parameter_error;
				}
			} else if (msgType == 2) {
				 commonMethodService.dealSystemLog(msg);
				 errorCode = ErrorCode.Success;
			} else {
				errorCode = ErrorCode.Parameter_error;
			}
		} else {
			errorCode = ErrorCode.Parameter_error;
		}
		return renderData(errorCode);
	}

	/**
	 * 记录系统和用户日志,多条上传<br/>
	 * 
	 * @param msgType
	 *            1:用户日志 2:系统日志，
	 * @param msgKey
	 *            msg的标识
	 * @param msgJson
	 *            多条日志详情
	 * @return
	 */
	@RequestMapping(value = "/recordByMsgs")
	public ResponseEntity<String> recordByMsgs(HttpServletRequest request, Integer msgType, String msgKey,
			String msgJson) {
		String errorCode = ErrorCode.System_error;
		if (msgType != null && StringUtil.isNotEmpty(msgJson)) {
			List<Map<String, Object>> msgList = JsonUtil.jsonToObject(msgJson, List.class);
			if (msgList != null && msgList.size() > 0) {
				if (msgType == 1) {
					String msg = "";
					for (Map<String, Object> msgmap : msgList) {
						msg = msgmap.get("msg").toString();
						if (StringUtil.isNotEmpty(msg)) {
							try {
								commonMethodService.dealAutoPostSLS(msg);
								errorCode = ErrorCode.Success;
							} catch (Exception e) {
								logger.error("recordByMsg Exception,msgKey:%s,msg:%s", msgType, msg);
								errorCode = ErrorCode.Parameter_error;
							}
						}
					}
				} else if (msgType == 2) {
					 String msg = "";
					 for (Map<String, Object> msgmap : msgList) {
					 msg = msgmap.get("msg").toString();
					 if (StringUtil.isNotEmpty(msg)) {
					 try {
					 commonMethodService.dealSystemLog(msg);
					 errorCode = ErrorCode.Success;
					 } catch (Exception e) {
					 logger.error("recordByMsg Exception,msgKey:%s,msg:%s",
					 msgType, msg);
					 errorCode = ErrorCode.Parameter_error;
					 }
					 }
					 }
				} else {
					logger.error("recordByMsg Exception,msgType:{},msgJson:{}", msgType, msgJson);
					errorCode = ErrorCode.Parameter_error;
				}
			} else {
				logger.error("recordByMsg Exception,msgType:{},msgJson:{}", msgType, msgJson);
				errorCode = ErrorCode.Parameter_error;
			}
		}
		return renderData(errorCode);
	}

	/**
	 * 记录系统和用户日志,文件方式上传<br/>
	 * 
	 * @param msgType
	 *            1:用户日志 2:系统日志，
	 * @param msgKey
	 *            msg的标识
	 * @param file
	 *            多条日志，一行一条。
	 * @return
	 */
	@RequestMapping(value = "/recordByFile")
	public ResponseEntity<String> recordByFile(HttpServletRequest request, Integer msgType, String msgKey,
			@RequestParam(value = "logFile", required = true) MultipartFile file) {
		String errorCode = ErrorCode.System_error;
		try {
			if (msgType != null && msgType == 2) {
				// TODO 系统日志的读写。
				BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
				String msg = "";
				try {
					while ((msg = br.readLine()) != null) {
						commonMethodService.dealSystemLog(msg);
					}
					errorCode = ErrorCode.Success;
				} catch (Exception e) {
					logger.error("recordByMsg Exception,msgType:{},msg:{}", msgType, e.getMessage());
					errorCode = ErrorCode.File_error;
				}
			} else {
				BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()));
				String msg = "";
				try {
					while ((msg = br.readLine()) != null) {
						commonMethodService.dealAutoPostSLS(msg);
					}
					errorCode = ErrorCode.Success;
				} catch (Exception e) {
					logger.error("recordByMsg Exception,msgType:{},msg:{}", msgType, e.getMessage());
					errorCode = ErrorCode.File_error;
				}
			}

		} catch (IllegalStateException | IOException e1) {
			logger.error("解析日志文件出错:" + e1);
		}
		return renderData(errorCode);
	}

}
